package memorymonitor;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MemoryMonitor {
    
    public  static final Integer TOTAL_MEMORY;
    
    private static final Logger logger = Logger.getLogger(MemoryMonitor.class.getName());

    private static final File memInfoFile = new File("/proc/meminfo");

    private long interval = 1000;
    private boolean stop  = false;

    public MemoryMonitor() {
    }

    public MemoryMonitor(long interval) {
        this.interval = interval;
    }

    static {
        try {
            TOTAL_MEMORY = readTotalMemoryFromProcFileSystem();
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
            throw new ExceptionInInitializerError("Não foi possível inicializar o monitor");
        }
    }


    public void run() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    execute();                    
                } catch (Exception ex) {
                    logger.log(Level.SEVERE, null, ex);
                    throw new RuntimeException("Ocorreu um erro com o monitor", ex);
                }
            }
        }, "MemoryMonitor").start();
    }

    public void stop() {
        stop = true;
    }

    private void execute() throws Exception {

        if (!"linux".equalsIgnoreCase(System.getProperty("os.name"))) {
            throw new RuntimeException("Este sistema operacional não é suportado. Requerido Linux");
        }

        logger.info("O monitor está rodando ...");

        while (!stop) {
            Thread.sleep(interval);
            int freeMemory = readFreeMemoryFromProcFileSystem();
        }

    }

    private static Integer readTotalMemoryFromProcFileSystem() throws FileNotFoundException {
        Scanner sc = new Scanner(memInfoFile);
        String total = sc.findWithinHorizon("MemTotal.*", 0).replaceAll("[^0-9]", "");        
        sc.close();
        return Integer.valueOf(total);
    }

    private static Integer readFreeMemoryFromProcFileSystem() throws FileNotFoundException {
        Scanner sc = new Scanner(memInfoFile);
        String free = sc.findWithinHorizon("MemFree.*", 0).replaceAll("[^0-9]", "");
        sc.close();
        return Integer.valueOf(free);
    }
}
